package com.mytool.controller;

import com.mytool.convert.TableConvert;
import com.mytool.domain.TableDomain;
import com.mytool.dto.TableDto;
import com.mytool.model.DDLGeneratorInput;
import com.mytool.model.GeneratedCodeResult;
import com.mytool.service.DDLGeneratorService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

/**
 * 代码生成器控制器
 */
@Controller
@RequestMapping("/cola-generator")
@Slf4j
public class DDLGeneratorController {

    @Autowired
    private DDLGeneratorService ddlGeneratorService;

    /**
     * 显示代码生成器页面
     */
    @GetMapping
    public String showGeneratorPage(Model model) {
        DDLGeneratorInput input = new DDLGeneratorInput();
        input.setFrameworkType("SPRING_BOOT"); // 默认使用Spring Boot 3.3.0架构
        model.addAttribute("input", input);
        return "cola-generator";
    }

    public static void parse(String ddl) throws Exception {
        CreateTable createTable = (CreateTable) CCJSqlParserUtil.parse(ddl);
        TableDomain tableDomain = new TableDomain(createTable);
        TableDto tableDto = TableConvert.INSTANCE.do2Dto(tableDomain);
        log.info(tableDto.toString());
    }

    /**
     * 处理DDL生成请求
     */
    @PostMapping
    public String generateColaCode(DDLGeneratorInput input, Model model) {
        try {
            parse(input.getDdlSql());
            GeneratedCodeResult result = ddlGeneratorService.generateColaCode(input);
            model.addAttribute("result", result);
            model.addAttribute("input", input);

            if (result.isSuccess()) {
                // 添加架构类型到模型，用于在结果页面显示
                model.addAttribute("frameworkType", input.getFrameworkType());
                return "cola-generator-result";
            } else {
                model.addAttribute("errorMessage", result.getErrorMessage());
                return "cola-generator";
            }
        } catch (Exception e) {
            model.addAttribute("errorMessage", "生成代码时发生错误: " + e.getMessage());
            model.addAttribute("input", input);
            return "cola-generator";
        }
    }

    /**
     * REST API: 生成代码
     */
    @PostMapping("/api")
    @ResponseBody
    public GeneratedCodeResult generateColaCodeApi(@RequestBody DDLGeneratorInput input) {
        return ddlGeneratorService.generateColaCode(input);
    }
}
